/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.gm.controller;

import com.icee.myth.gm.GmServer;
import com.icee.myth.common.channelHandler.HttpServerHandler;
import com.icee.myth.gm.client.GameServerClient;
import com.icee.myth.utils.Consts;
import com.icee.myth.utils.Escape;
import com.icee.myth.utils.LogConsts;
import com.icee.myth.utils.MLogger;

/**
 *
 * @author yangyi
 */
public class PostController extends AbstractController {

    public PostController(int privilege) {
        super(privilege);
    }

    @Override
    public void process() {
        Long serverId = (Long) jobj.get("server");
        String content = (String)jobj.get("content");
        content = Escape.unescape(content);
        GameServerClient gameServerClient = null;
        if (serverId != null) {
            gameServerClient = GmServer.INSTANCE.getServer(serverId.intValue());

            if (content != null) {
                if(gameServerClient != null) {
                    if (gameServerClient.broadcast(content)) {
                        dbHandler.insertGmOperateLog(userData.userName, Consts.GMOPERATELOG_POST, jobj.toJSONString());
                        HttpServerHandler.writeResponse(request, ctx.channel(), "text/html; charset=UTF-8", "{\"result\":0}", null);
                    }
                    MLogger.getlogger().log(LogConsts.LOGTYPE_BEHAVIOR, "[" + ctx.channel().remoteAddress() + "] User [" + userData.userName + "] post " + jobj.get("content") + " to server id "+gameServerClient.serverConfig.id);
                } else if (serverId == -1) {
                    for(GameServerClient tmpServer : GmServer.INSTANCE.getGameServerClients().values()){
                        tmpServer.broadcast(content);
                    }
                    dbHandler.insertGmOperateLog(userData.userName, Consts.GMOPERATELOG_POST,jobj.toJSONString());
                    MLogger.getlogger().log(LogConsts.LOGTYPE_BEHAVIOR, "[" + ctx.channel().remoteAddress() + "] User [" + userData.userName + "] post " + jobj.get("content"));
                    HttpServerHandler.writeResponse(request, ctx.channel(), "text/html; charset=UTF-8", "{\"result\":" + 0 + "}", null);
                } else {
                    HttpServerHandler.writeResponse(request, ctx.channel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"server " + serverId + " not found\"}", null);
                }
            } else {
                HttpServerHandler.writeResponse(request, ctx.channel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"param error\"}", null);
            }
        } else {
            HttpServerHandler.writeResponse(request, ctx.channel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"param error\"}", null);
        }
    }
}
